﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dotNails.CodeGen.Models;

namespace dotNails.CodeGen.Models.dotNailsLinqToSqlGenerator {
	public class DataContextTemplate : BaseCodeTemplate {
		public DataBase DB { get; set; }
		public string DbmlName { get; set; }

		public bool ReturnsScalar(Function function) {
			bool returnsScalar = false;

			if (function.Return != null && !string.IsNullOrEmpty(function.Return.Type) && function.Return.Type.Contains("ScalarResult")) {
				returnsScalar = true;
			}

			return returnsScalar;
		}

		public string GetScalarType(Function function) {
			string scalarType = string.Empty;

			// Trim off the front and back and return what is in the generic type 
			scalarType = function.Return.Type.Replace("ISingleResult<ScalarResult<", "");
			scalarType = scalarType.Replace(">>", "");
			
			return scalarType;
		}

		public string GetProcReturnType(Function function) {
			string returnType = string.Empty;

			if (ReturnsScalar(function)) {
				returnType = GetScalarType(function);
			}
			else {
				returnType = GetReturnType(function);
			}

			return returnType;
		}

		public string GetReturnType(Function function) {
			string returnType = string.Empty;

			if (function.ElementType != null) {
				if (!string.IsNullOrEmpty(function.ElementType.IdRef)) {
					returnType = "ISingleResult<" + function.ElementType.IdRef + ">";
				}
				else {
					returnType = "ISingleResult<" + function.ElementType.Name + ">";
				}
			}
			else if (function.Return != null && !string.IsNullOrEmpty(function.Return.Type)) {
				if (function.Return.Type.Contains("ScalarResult")) {
					// (e.g. ISingleResult<ScalarResult<DateTime>>)
					returnType = function.Return.Type;
				}
				else {
					returnType = GetCSharpVariableType(function.Return.Type, false);
				}
			}
			
			return returnType;
		}
	}
}
